﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System.Reflection;

namespace 日志的使用.自定义的内容.过滤器Filter
{
    /// <summary>
    /// 授权的Filter
    /// </summary>
    public class SelfAuthorizationFilter : IAsyncAuthorizationFilter
    {
        /// <summary>
        /// 在筛选器管道中提前调用以确认请求是否已授权
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public Task OnAuthorizationAsync(AuthorizationFilterContext context)
        {
            //throw new NotImplementedException();
            //context.HttpContext.User.Identity.Name == "shsdfs";
            //获取请求参数列表
            string? paramValue = context.HttpContext.Request.QueryString.Value;
            paramValue.Replace("?", "").Trim();
            //获取参数
            string[] paramValues = paramValue.Split("%");
            //获取字典<参数主键, 参数值>
            Dictionary<string, object> paramDic = new Dictionary<string, object>();
            //遍历切割方法请求路径, 获取到请求参数的key和值
            foreach (var param in paramValues)
            {
                paramDic.Add(param.Split("=")[0].Trim(), param.Split("=")[1].Trim());
            }

            if (paramValue.Length % 2 > 1) {
                //未通过验证则跳转到无权限提示页
                RedirectToActionResult content = new RedirectToActionResult("NoAuth", "Exception", null);
                context.Result = content;
            }
            return Task.CompletedTask;
        }
    }
}
